//查询确定协调批号信息
function queryPosOrderPostingDetail(row) {
    var html = $.openx.innerHtml('createCoordinateOrderModel');
    $X("/order/queryService", "getOrderPickDetail").callx({
        orderCode: row.orderCode,
        onResult: function (result) {
            result.channelName = channelMap.get(result.topChannelCode)
            var receiver = result.receiver;
            if (receiver) {
                result.receiverName = receiver.name
                result.receiverPhone = receiver.phone
                result.address = (receiver.provinceName ? receiver.provinceName : "") + (receiver.cityName ? receiver.cityName : "") + (receiver.districtName ? receiver.districtName : "") + (receiver.detailAddress ? receiver.detailAddress : "");
            }
            result.createTime = $.openx.formatDate(new Date(result.createTime));
            orderDetail = result;
        },
        onError: function (error) {
        }
    });
    ajax(jot_posting_server + "/posting/postingQueryService", "getPosChannelPostingInfo").callx({
        orderCode: row.orderCode,
        onResult: function (result) {
            layer.closeAll('loading');
            orderCode = result.orderCode;
            laytpl($.openx.innerHtml('createCoordinateOrderModel')).render(result, function (html) {
                $.openx.openLayer(null, '确定协调批号', html, true);

                $('#posStoreUserSelect').change(function () {
                    if ($(this).val() === 'other') {
                        $('#posOtherStoreUserLabel').show();
                        $('#posOtherStoreUserInput').show();
                    } else {
                        $('#posOtherStoreUserLabel').hide();
                        $('#posOtherStoreUserInput').hide();
                    }
                });
            });
        },
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}


//确认确定协调批号
function sumitCreateXTOrder() {
    /**提交表单*/
    var array = [];
    $("#posGoodsInfo").find("tbody tr").each(
        function (i, item) {
            var goods = new Object();
            /**当前行批号*/
            var td = $(item).find("td");
            /**商品编码*/
            goods.goodsCode = $(td).eq(0).text();
            /**商品总数*/
            goods.total = $(td).eq(2).text();
            /**批号*/
            goods.goodsLotNum = $(td).eq(3).find("select[name='posLotNumSelect']").find("option:selected").text().trim();
            /**商品数量*/
            goods.goodsNum = $(td).eq(4).find("select[name='posAmountSelect']").val();
            goods.accountPrice = $(td).eq(5).text();
            goods.exercisePrice = $(td).eq(6).text();
            goods.flag = false;
            array.push(goods);
            /**定位错误信息位置*/
            $(td).eq(0).attr("class", "tips" + goods.goodsCode);
        });

    for (var i = 0; i < array.length; i++) {
        var w = array[i];
        /**商品数量非空校验*/
        if (!w.goodsNum) {
            layer.tips("商 品 编 码 " + w.goodsCode + " 未 选 择 数 量", ".tips" + w.goodsCode);
            return;
        }
        /**批次号非空校验*/
        if (!w.goodsLotNum) {
            layer.tips("商 品 编 码 " + w.goodsCode + " 未 选 择 批 次 号", ".tips" + w.goodsCode);
            return;
        }

        var goodsNum = parseFloat(w.goodsNum);//数量
        /**检查批次是否相同校验*/
        var goodlot = w.goodsCode + w.goodsLotNum + w.exercisePrice;//批次
        for (var j = i + 1; j < array.length; j++) {
            /**商品数量非空校验*/
            if (!array[j].goodsNum) {
                layer.tips("商 品 编 码 " + array[j].goodsCode + " 未 选 择 数 量", ".tips" + array[j].goodsCode);
                return;
            }
            /**批次号非空校验*/
            if (!array[j].goodsLotNum) {
                layer.tips("商 品 编 码 " + array[j].goodsCode + " 未 选 择 批 次 号", ".tips" + array[j].goodsCode);
                return;
            }
        }

        /**商品数量校验*/
        if (!w.flag) {
            w.flag = true;
        } else {
            continue;
        }

        for (var j = i + 1; j < array.length; j++) {
            var nn = array[j];
            if (!nn.flag) {
                if (w.goodsCode == nn.goodsCode && w.exercisePrice == nn.exercisePrice) {
                    nn.flag = true;
                    goodsNum += parseFloat(nn.goodsNum);
                }
            }
        }
        if (goodsNum > w.total) {
            layer.tips("商 品 编 码 " + w.goodsCode + " 数 量 不 能 超 过 " + w.total + " 个，目 前 为 " + goodsNum + " 个。", ".tips" + w.goodsCode);
            return;
        }
        if (goodsNum < w.total) {
            layer.tips("商 品 编 码 " + w.goodsCode + " 数 量 不 足 " + w.total + " 个，目 前 为 " + goodsNum + " 个。", ".tips" + w.goodsCode);
            return;
        }

    }
    var selectUserCode = $("#posStoreUserSelect").val();
    if (selectUserCode === '') {
        layer.tips("营 业 员 不 能 为 空", '#posStoreUserSelect');
        return;
    }
    var userCode = selectUserCode.split("-");


    if (selectUserCode === 'other') {
        var inputUserCode = $('#posOtherStoreUser').val();
        var sp = inputUserCode.split('-');
        if (sp.length != 2 || sp[1].length > 8 || sp[1].length < 1) {
            layer.tips("非 门 店 员 工 填 写 " + inputUserCode + " 不 符 合 要 求", '#otherStoreUser');
            return;
        } else {
            userCode[0] = sp[0];
            userCode[1] = sp[1];
        }
    }
    /**下账确认*/

    $.openx.confirm("是否确认协调出库的商品为所选批号？", function () {
        var operatorCode = "";
        if (userCode[0] === '') {
            operatorCode = ""
        } else {
            operatorCode = userCode[1];
        }
        var postingModel = new Object();
        postingModel.orderCode = orderCode;
        postingModel.operatorCode = operatorCode;
        postingModel.receiverName = $('#posReceiverName').html();
        postingModel.receiverPhone = $('#posReceiverPhone').html();
        postingModel.goods = array;
        console.log(postingModel)
        ajax(jot_posting_server + "/posting/postingService", "posChannelSendSalePosting")
            .callx({
                postingModel: postingModel,
                onResult: function (result) {
                    if (result === 'SUCCESS') {
                        layer.msg('确定协调批号成功', {time: 1000}, function () {
                            layer.closeAll();
                            //手动刷新表格
                            $.openx.tableRefresh(null, null, true);
                        });
                    } else {
                        layer.msg("确定协调批号失败: " + result);
                    }
                },
                //请求失败执行
                onError: function (error) {
                    layer.msg("确定协调批号失败")
                }
            });
    });
}

var order;
function autoCreateConsort(row) {
    order = row;
    var html = $.openx.innerHtml('autoCreateConsortModel');
    ajax(jot_posting_server + "/posting/postingQueryService", "querySalesCodes").callx({
        orderCode: row.orderCode,
        onResult: function (result) {
            layer.closeAll('loading');
            var model = {};
            model.salesCodes = result;
            model.orderCode = row.orderCode;
            laytpl($.openx.innerHtml('autoCreateConsortModel')).render(model, function (html) {
                $.openx.openLayer(null, '选择营业员', html, true);
            });
        },
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}

function createOrderDeliveryTask(orderCode) {
    var orderCodes =[];
    orderCodes[0]=orderCode;
    $X("/order/operateService", "createOrderDeliveryTask").callx({
        orderCode: orderCode,
        onResult: function (result) {
            if (result === 0) {
                openTicketDialog(orderCode, orderCodes)
            } else {
                layer.msg('发货失败，请联系管理员!');
            }
        },
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}

function submitAutoCreateConsort(orderCode) {
    var orderCodes =[];
    orderCodes.push(orderCode);
    var selectUserCode = $("#autoCreateConsortUserSelect").val();
    if (selectUserCode === '') {
        layer.tips("营业员不能为空", '#autoCreateConsortUserSelect');
        return;
    }
    var userCode = selectUserCode.split("-");
    var operatorCode = "";
    if (userCode[0] === '') {
        operatorCode = ""
    } else {
        operatorCode = userCode[1];
    }
    saveOperatorCode(orderCode, operatorCode)
    layer.closeAll();
    //1、判断是否是自提单
    if (order.stateCode === 'DELIVERY_WAITING' && order.deliveryType === 'SELF_PICK') {
        openTicketDialog(orderCode, orderCodes);
        $.openx.tableRefresh(null, null, true);
        return;
    }else if (order.stateCode === 'DELIVERY_WAITING' && order.deliveryProvider) {//待发货并且是益丰配送则请求物流平台进行发货处理
        $.openx.confirm('打印小票，同时会进行发货操作。是否继续？', function () {
            layer.closeAll();
            //通知物流平台进行发货操作
            // $X("/order/operateService", "createOrderDeliveryTask").callx({
            //     orderCode: orderCodes[0],
            //     onResult: function (result) {
            //         if (result === 0) {
            //             openTicketDialog(orderCode, orderCodes)
            //             $.openx.tableRefresh(null, null, true);
            //         } else {
            //             layer.msg('发货失败，请联系管理员!');
            //         }
            //     },
            //     onError: function (error) {
            //         layer.msg(error.msg);
            //     }
            // });
            createTask(orderCode, orderCodes);
        });
    } else {
        openTicketDialog(orderCode, orderCodes)
        $.openx.tableRefresh(null, null, true);
    }
}

function createConsort(orderCode, userCode) {
    $X("/posting/postingQueryService", "autoCreateConsort")
        .callx({
            orderCode: orderCode,
            operatorCode: userCode,
            onResult: function (result) {
                layer.closeAll();
                if (result !== 'SUCCESS') {
                    layer.msg("自动确定协调批号失败,请手动确定协调批号: " + result);
                }
                $.openx.tableRefresh(null, null, true);
            },
            //请求失败执行
            onError: function (error) {
                layer.msg("自动确定协调批号失败,请手动确定协调批号。");
            }
        });
}
function goBack(row) {
    var html = $.openx.innerHtml('goBackModel');
    var result = {};
    result.orderCode = row.orderCode;
    laytpl($.openx.innerHtml('goBackModel')).render(result, function (html) {
        $.openx.openLayer(null, '拒绝发货', html, true);
        $('#goBackReasonSelect').change(function () {
            if ($(this).val() === 'other') {
                $('#goBackOtherReasonDiv').show();
            } else {
                $('#goBackOtherReasonDiv').hide();
            }
        });
    });
}

function rejectTransfer(row) {
    var result = {};
    result.orderCode = row.orderCode;
    laytpl($.openx.innerHtml('rejectTransferModel')).render(result, function (html) {
        $.openx.openLayer(null, '拒绝调货', html, true);
        $('#rejectTransferReasonSelect').change(function () {
            if ($(this).val() === 'other') {
                $('#rejectTransferOtherReasonDiv').show();
            } else {
                $('#rejectTransferOtherReasonDiv').hide();
            }
        });
    });
}


function submitGoBack(orderCode) {
    var selectReason = $("#goBackReasonSelect").val();
    if (!selectReason) {
        layer.tips("发货原因不能为空", '#goBackReasonSelect');
        return;
    }
    if (selectReason === 'other') {
        selectReason = $("#goBackOtherReasonInput").val();
    }
    if (!selectReason) {
        layer.tips("发货原因不能为空", '#goBackOtherReasonInput');
        return;
    }
    ajax(x_jot_sic_server + "/OrderService", "goBack")
        .callx({
            orderCode: orderCode,
            reason: selectReason,
            onResult: function (result) {
                if (result == null || result === 'null') {
                    console.info("拒绝发货成功");
                    layer.closeAll();
                    layer.msg("拒绝发货成功");
                } else {
                    layer.msg("拒绝发货失败: " + result);
                }
                $.openx.tableRefresh(null, null, true);
            },
            onError: function (error) {
                console.info(error);
                layer.msg("拒绝发货失败: " + error);
            }
        }, 120000);
}

function submitRejectTransfer(orderCode) {
    var selectReason = $("#rejectTransferReasonSelect").val();
    if (!selectReason) {
        layer.tips("拒绝原因不能为空", '#rejectTransferReasonSelect');
        return;
    }
    if (selectReason === 'other') {
        selectReason = $("#rejectTransferOtherReasonInput").val();
    }
    if (!selectReason) {
        layer.tips("拒绝原因不能为空", '#rejectTransferOtherReasonInput');
        return;
    }
    ajax(x_jot_sic_server + "/TransferOrderService", "rejectTransfer")
        .callx({
            orderCode: orderCode,
            reason: selectReason,
            onResult: function (result) {
                if (result == null || result === 'null') {
                    console.info("拒绝调货成功");
                    layer.closeAll();
                    layer.msg("拒绝调货成功");
                } else {
                    layer.msg("拒绝调货失败: " + result);
                }
                $.openx.tableRefresh(null, null, true);
            },
            onError: function (error) {
                console.info(error);
                layer.msg("拒绝调货失败: " + error);
            }
        }, 120000);
}

/**
 * 自动下账
 * @param row
 */
function autoCreatePosting(row) {
    order = row;
    var html = $.openx.innerHtml('autoCreatePostingModel');
    ajax(jot_posting_server + "/posting/postingQueryService", "queryAutoPostingDetail").callx({
        orderCode: row.orderCode,
        onResult: function (result) {
            layer.closeAll('loading');
            orderCode = result.orderCode;
            laytpl($.openx.innerHtml('autoCreatePostingModel')).render(result, function (html) {
                $.openx.openLayer(null, '自动下账', html, true);
            });
        },
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}

/**
 * 自动下账
 * @param row
 */
function submitAutoPosting(orderCode) {
    var selectUserCode = $("#autoStoreUserSelect").val();
    if (selectUserCode === '') {
        layer.tips("营 业 员 不 能 为 空", '#autoStoreUserSelect');
        return;
    }
    var sex = $('input[name=sex]:checked').val();
    var userCode = selectUserCode.split("-");
    var operatorCode = "";
    if (userCode[0] === '') {
        operatorCode = ""
    } else {
        operatorCode = userCode[1];
    }
    var patientName = $('#autoPatientName').val();
    var patientPhone = $('#autoPatientPhone').val();
    var patientIDCard = $('#autoPatientIDCard').val();
    var patientAge = $('#patientAge').val();
    var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
    var regPhone1 = /^1\d{10}$/;
    var regPhone2 = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
    if (patientName != undefined && patientName.trim().length > 0) {
        if (patientName.length != 0 && patientName.trim().length < 2 && patientName.trim().length < 10) {
            layer.tips("姓 名 填 写 错 误", '#autoPatientName');
            return;
        }
    }
    if (patientPhone != undefined && patientPhone.trim().length > 0) {
        if (regPhone1.test(patientPhone) == false && regPhone2.test(patientPhone) == false) {
            layer.tips("电 话 号 码 不 符 合 要 求", '#autoPatientPhone');
            return;
        }
    }
    if (patientIDCard != undefined && patientIDCard.trim().length > 0) {
        if (regIdCard.test(patientIDCard) == false) {
            layer.tips("身 份 证 号 码 不 符 合 要 求", '#autoPatientIDCard');
            return;
        }
    }

    if (patientAge != undefined && patientAge.trim().length > 0) {
        if(!isIntNum(patientAge)){
            layer.tips("年 龄 必 须 为 数 字", '#patientAge');
            return;
        }
    }

    var patientAddress = $('#patientAddress').val();
    if (patientAddress != undefined && patientAddress.trim().length > 50) {
        layer.tips("患 者 地 址 不 能 超 过 50 个 字 符", '#patientAddress');
        return;
    }

    //add by zhouwenkai start

    var prescriptionFlag = $('#prescriptionFlag').val();
    console.log("auto prescriptionFlag="+prescriptionFlag);

    var instrumentFlag = $('#instrumentFlag').val();
    console.log("auto instrumentFlag="+instrumentFlag);

    if(prescriptionFlag === 'true'){
        // //患者姓名，性别，年龄 必须
        // console.log("我是处方单")
        // if(patientName === undefined || patientName.length==0){
        //     layer.tips("姓 名 必 填", '#autoPatientName');
        //     return;
        // }
        //
        // if(sex === undefined || sex.length==0){
        //     layer.tips("性 别 必 填", '#sexlable');
        //     //alert("患 者 性 别 必 填")
        //     return;
        // }
        //
        // if(patientAge === undefined || patientAge.length==0){
        //     layer.tips("年 龄 必 填", '#patientAge');
        //     return;
        // }
    }


    var customerPhone = $('#customerPhone').val();
    var customerName = $('#customerName').val();

    if(instrumentFlag==='Y'){
        console.log("我是三类医疗")
        if(customerName === undefined ||customerName.length==0){
            layer.tips("顾 客 姓 名 必 填", '#customerName');
            return;
        }

        if(customerPhone === undefined ||customerPhone.length==0){
            layer.tips("联 系 电 话 必 填", '#customerPhone');
            return;
        }else {
            if (regPhone1.test(customerPhone) == false && regPhone2.test(customerPhone) == false) {
                layer.tips("联 系 电 话 不 符 合 要 求", '#customerPhone');
                return;
            }
        }
    }

    //add by zhouwenkai end

    var postingModel = new Object();
    postingModel.orderCode = orderCode;
    postingModel.operatorCode = operatorCode;
    postingModel.receiverName = $('#receiverName').html();
    postingModel.receiverPhone = $('#receiverPhone').html();
    postingModel.prescriptor = $('#pPrescriptor').val();
    postingModel.saleMan = $('#pSaleMan').val();
    postingModel.reviewer = $('#pReviewer').val();
    postingModel.patientName = patientName;
    postingModel.patientPhone = patientPhone;
    postingModel.patientIDCard = patientIDCard;
    postingModel.sex =  sex;
    postingModel.patientAge = patientAge;

    postingModel.customerPhone =  customerPhone;
    postingModel.customerName = customerName;

    postingModel.linkageAddress = patientAddress ;


    var orderCodes = [orderCode];
    savePostingModel(postingModel);
    layer.closeAll();
    //1、判断是否是自提单
    if (order.stateCode === 'DELIVERY_WAITING' && order.deliveryType === 'SELF_PICK') {
        openTicketDialog(orderCode, orderCodes);
        $.openx.tableRefresh(null, null, true);
        return;
    }else if (order.stateCode === 'DELIVERY_WAITING' && order.deliveryProvider) {//待发货并且是益丰配送则请求物流平台进行发货处理
        $.openx.confirm('打印小票，同时会进行发货操作。是否继续？', function () {
            layer.closeAll();
            //通知物流平台进行发货操作
            // $X("/order/operateService", "createOrderDeliveryTask").callx({
            //     orderCode: orderCode,
            //     onResult: function (result) {
            //         if (result === 0) {
            //             $.openx.tableRefresh(null, null, true);
            //             openTicketDialog(orderCode, orderCodes);
            //         } else {
            //             layer.msg('发货失败，请联系管理员!');
            //         }
            //     },
            //     onError: function (error) {
            //         layer.msg(error.msg);
            //     }
            // });
            createTask(orderCode, orderCodes);
        });
    } else {
        openTicketDialog(orderCode, orderCodes);
        $.openx.tableRefresh(null, null, true);
    }
}

function isIntNum(val){
    var regPos = /^\d+$/; // 非负整数
    if(regPos.test(val)){
        return true;
    }else{
        return false;
    }
}


function saveOperatorCode(orderCode,operatorCode) {
    var postingModel = {};
    postingModel.orderCode = orderCode;
    postingModel.operatorCode = operatorCode;
    savePostingModel(postingModel);
}
function savePostingModel(postingModel) {

    console.log("最终post-savePostingModel"+JSON.stringify(postingModel));

    ajax(jot_posting_server + "/posting/postingService", "savePostingModel")
        .callx({
            postingModel: postingModel,
            onResult: function (result) {
                if (result == null || result === 'null') {
                    console.info("保存下账数据成功")
                } else {
                    layer.msg("保存下账数据失败: " + result);
                }
            },
            //请求失败执行
            onError: function (error) {
                console.info(error);
                layer.msg("保存下账数据失败: " + error);
            }
        });
}

function createPosting(postingModel) {
    $X("/posting/postingQueryService", "autoSendSalePosting")
        .callx({
            postingModel: postingModel,
            onResult: function (result) {
                layer.closeAll();
                if (result !== 'SUCCESS') {
                    layer.msg("自动确定协调批号失败,请手动确定协调批号: " + result);
                }
                $.openx.tableRefresh(null, null, true);
            },
            //请求失败执行
            onError: function (error) {
                layer.msg("自动确定协调批号失败,请手动确定协调批号。");
            }
        });
}
/**
 * New Openx js client, more modern ! 2015-05-19
 */
function ajax(mapping, method) {
    var _m = mapping;
    var _t = method;
    this.callx = function (data, timeout) {
        var url = _m + '/' + _t;
        if (openx.isNull(data)) {
            data = {};
        }
        openx.invoke(url, openx.conf()['type'], data, timeout, data.onResult, data.onError);
    };
    return this;
}

